package web;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.FitsZipFile;

@SuppressWarnings("serial")
public class ZipServlet extends HttpServlet {

    private static char SEP = File.separatorChar;
    
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

		String[] filepaths = null; // an array to hold the names of files that are selected?
		Enumeration<String> paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			if (paramName.equals("option")) {
				filepaths = request.getParameterValues(paramName);
			}
		}

//		for (int i = 0; i < filepaths.length; i++) {
//			System.out.println(filepaths[i]);
//		}

		// got to identify the real path to the zips folder to save the zip file
		// got to identify the "URL" path to the zips folder to give to the end user	
		
		String path = getServletContext().getRealPath("/")+"zips"+SEP;
		String urlPath = "http://"+request.getServerName()+":"+request.getServerPort()+"/"+"ICRAR-fits"+"/"+"zips"+"/";

		ArrayList<String> filePaths = new ArrayList<String>(Arrays.asList(filepaths));

		FitsZipFile fzFile = new FitsZipFile();
		String zipFilename = fzFile.makeZipFile(filePaths,path);
		
		String zipFilepath = urlPath+zipFilename;
		
		request.setAttribute("zipFileURL", zipFilepath); // alFFs = the array list of Fits Files to be displayed
		getServletContext().getRequestDispatcher("/jsp/zipFile.jsp").forward(request, response);
	}
}
